import re

import requests
import json
import logging

from app.config import Config
from app.db.database import SessionLocal
from app.db.crud import create_tjudge, update_tpost_is_judge
from app.db.models import TLabel, TCategory, TMiddlePostLabel, TPost
from app.dify.tag_saver import TagSaver

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        # logging.FileHandler('data/llm_with_jina.log')
    ]
)
logger = logging.getLogger(__name__)

class LLMWithJina:
    def __init__(self, post_id: int,  url: str):
        self.post_id = post_id
        self.url = url
        config = Config()
        self.judge_url = config.llm_with_jina_url
        self.api_key = config.llm_with_jina_api_key

    def run_workflow(self) -> bool:
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

        # 请求体
        data = {
            "inputs": {
                "input_url": self.url
            },
            "response_mode": "blocking",  # 或者 "streaming"
            "user": "unique_user_id",  # 替换为实际的用户标识
            "files": []  # 如果需要上传文件，可以在这里添加文件信息
        }

        # 发送 POST 请求
        response = requests.post(self.judge_url, headers=headers, data=json.dumps(data))

        # 检查响应状态码
        if response.status_code == 200:
            # 解析响应内容
            response_data = response.json()

            # 1. 获取 outputs 字段
            outputs = response_data['data']['outputs']

            # 2. 解析 outputs 中的 text 字段
            text_content = outputs['text']
            
            # 使用 logger 记录响应内容
            logger.info(f"[LLM Response for Post {self.post_id}]")
            logger.info(f"Raw response: {text_content}")

            # 定义替换规则
            def fix_json_string(json_str):
                # 使用正则表达式替换 <...> 为合法的 JSON 字符串
                fixed_str = re.sub(r'<([^>]*)>', r'"\1"', json_str)
                return fixed_str

            # 修复 JSON 字符串
            fixed_content = fix_json_string(text_content)
            try:
                # 尝试解析 JSON
                parsed_data = json.loads(fixed_content)
                logger.info(f"Parsed JSON successfully: {json.dumps(parsed_data, ensure_ascii=False, indent=2)}")
            except json.JSONDecodeError as e:
                # 如果解析失败，记录错误信息和内容
                logger.error(f"JSON parsing failed: {str(e)}")
                logger.error(f"Content that failed to parse: {fixed_content}")

            # 3. 提取分值和类别
            tags_str = parsed_data.get("标签", "") or ""
            tags = self.process_tags(tags_str)
            category_str = parsed_data.get("分类", "") or ""
            categorys = self.process_tags(category_str)
            # 提取分类
            reason = parsed_data.get("总结", "")  # 提取原因

            # 使用 TagSaver 保存数据
            with SessionLocal() as db:
                tag_saver = TagSaver(db, post_id=self.post_id, tags=tags, categorys=categorys, reason=reason)
                tag_saver.save()

            return True
        else:
            error_msg = f"Failed to run workflow. Status code: {response.status_code}, Response: {response.text}"
            print(error_msg)
            logger.error(error_msg)

        return False

    def process_tags(self,tags_input):
        if isinstance(tags_input, list):
            # 如果输入是列表，直接清理并返回
            return [tag.strip("<>").strip() for tag in tags_input if tag.strip("<>").strip()]
        elif isinstance(tags_input, str):
            # 如果输入是字符串，先分割再清理
            return [tag.strip("<>").strip() for tag in tags_input.split(",") if tag.strip("<>").strip()]
        else:
            # 对于其他类型，返回空列表或者抛出异常
            return []

if __name__ == "__main__":
    post_id = 205
    url = "https://www.ithome.com/0/821/350.htm"
    llm_with_jina = LLMWithJina(post_id, url)
    llm_with_jina.run_workflow()

